package com.hxd.otc.module.convenience.activity;

import android.Manifest;
import android.app.Activity;
import android.content.ContentResolver;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.Rect;
import android.net.Uri;
import android.os.Bundle;
import android.provider.ContactsContract;
import android.support.constraint.ConstraintLayout;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.View;
import android.view.ViewTreeObserver;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;

import com.hxd.otc.R;
import com.hxd.otc.base.OnItemClickListener;
import com.hxd.otc.base.permission.PermissionActivity;
import com.hxd.otc.common.UserHelper;
import com.hxd.otc.common.enums.ConvenienceBusinessTypeEnum;
import com.hxd.otc.common.enums.PhoneLocationEnum;
import com.hxd.otc.dialog.ForbiddenBankCardDialog;
import com.hxd.otc.module.convenience.adapter.PrepaidRechargeAdapter;
import com.hxd.otc.module.convenience.adapter.PrepaidRechargeHistoriesAdapter;
import com.hxd.otc.module.convenience.bean.NorGoodsBean;
import com.hxd.otc.module.convenience.bean.OrderInfoBean;
import com.hxd.otc.module.convenience.bean.PhoneLocationBean;
import com.hxd.otc.module.convenience.bean.PrepaidGoodsBean;
import com.hxd.otc.module.convenience.bean.RefuelingServiceBean;
import com.hxd.otc.module.convenience.contract.PrepaidRechargeContract;
import com.hxd.otc.module.convenience.fragment.ConvenienceFragment;
import com.hxd.otc.module.convenience.fragment.PayDialogFragment;
import com.hxd.otc.module.convenience.presenter.PrepaidRechargePresenter;
import com.hxd.otc.module.login.activity.LoginActivity;
import com.hxd.otc.other.OnPermissionsResult;
import com.hxd.otc.utils.DataUtils;
import com.hxd.otc.utils.UIUtils;
import com.hxd.otc.widget.TextWatcherAdapter;
import com.hxd.otc.widget.TitleBar;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;

/**
 * Created by lzy on 2018/12/12 0012.
 * description ${话费充值}
 */
public class PrepaidRechargeActivity extends PermissionActivity<PrepaidRechargePresenter> implements PrepaidRechargeContract.IView {
    @BindView(R.id.title_bar)
    TitleBar mTitleBar;
    @BindView(R.id.et_phone)
    EditText mEtPhone;
    @BindView(R.id.iv_address_list)
    ImageView mIvAddressList;
    @BindView(R.id.tv_home_location)
    TextView mTvHomeLocation;
    @BindView(R.id.recyclerView)
    RecyclerView mRecyclerView;
    @BindView(R.id.cl_phone)
    ConstraintLayout mClPhone;
    @BindView(R.id.recyclerView_histories)
    RecyclerView mRecyclerViewHistories;

    private ForbiddenBankCardDialog mClearHistoriesDialog;
    private PrepaidRechargeAdapter mRechargeAdapter;
    private PrepaidRechargeHistoriesAdapter mHistoriesAdapter;
    private PayDialogFragment mPayDialogFragment;

    @Override
    protected int getLayoutId() {
        return R.layout.activity_prepaid_recharge;
    }

    @Override
    protected PrepaidRechargePresenter createPresenter() {
        return new PrepaidRechargePresenter(this);
    }

    @Override
    protected void initView() {
        mRecyclerView.setLayoutManager(new GridLayoutManager(this, 3));
        mRechargeAdapter = new PrepaidRechargeAdapter(this);
        mRecyclerView.setAdapter(mRechargeAdapter);
        mRechargeAdapter.setEnable(false);

        mRecyclerViewHistories.setLayoutManager(new LinearLayoutManager(this));
        mHistoriesAdapter = new PrepaidRechargeHistoriesAdapter(this);
        mRecyclerViewHistories.setAdapter(mHistoriesAdapter);
        mHistoriesAdapter.addAll(true, UserHelper.getCurUserPrepaidRechargeHistories());
    }

    @Override
    protected void initData() {
        Bundle bundle = getBundle();
        if (bundle != null) {
            mPresenter.setRefuelingServiceBean((RefuelingServiceBean) bundle.getSerializable(ConvenienceFragment.EXTRA_REFUELING_SERVICE_BEAN));
            mPresenter.setBusinessType((ConvenienceBusinessTypeEnum) bundle.getSerializable(ConvenienceFragment.EXTRA_BUSINESS_TYPE));
        }
        mPresenter.getPrepaidRechargeInfo();

    }

    @Override
    protected void initEvent() {
        mEtPhone.addTextChangedListener(mPhoneWatcher);
        mRechargeAdapter.setOnItemClickListener(new OnItemClickListener() {
            @Override
            public void onItemClick(int position) {
                onPrepaidRecharge(mRechargeAdapter.getItem(position));
            }
        });
        mHistoriesAdapter.setOnItemClickListener(new OnItemClickListener() {
            @Override
            public void onItemClick(int position) {
                if (mHistoriesAdapter.getItemViewType(position) == PrepaidRechargeHistoriesAdapter.ITEM_TYPE_NOR) {
                    updateSelectedPhone(mHistoriesAdapter.getItem(position));
                } else {
                    updateSelectedPhone("");
                    showClearHistoriesDialog();
                }
            }
        });
    }

    /**
     * 话费充值
     *
     * @param item
     */
    private void onPrepaidRecharge(PrepaidGoodsBean item) {
        if (!UserHelper.isLogin()) {
            Bundle bundle = new Bundle();
            bundle.putBoolean(LoginActivity.EXTRA_FINISH_SKIP_MAIN, false);
            $startActivity(LoginActivity.class, bundle);
            return;
        }
        String phoneNumber = mEtPhone.getText().toString().trim().replace(" ", "");//获取手机号

        PhoneLocationBean phoneLocation = mPresenter.getPhoneLocation(phoneNumber);
        if (phoneLocation == null) {
            showToast(getString(R.string.no_phone_location_hint));
            return;
        }

        PhoneLocationEnum locationEnum = phoneLocation.getLocationEnum();
        NorGoodsBean realNorGoodsBean = null;
        for (NorGoodsBean norGoodsBean : item.getNorGoodsBeans()) {
            if (locationEnum.equals(norGoodsBean.getLocationEnum())) {
                realNorGoodsBean = norGoodsBean;
                break;
            }
        }
        if (realNorGoodsBean == null) {
            showToast(getString(R.string.the_goods_are_not_available_at_present));
            return;
        }

        OrderInfoBean prepaidRechargeOrder = OrderInfoBean.createPrepaidRechargeOrder
                (phoneNumber, realNorGoodsBean, mPresenter.getBusinessType(), mTitleBar.getTitle().getText().toString());
        if (mPayDialogFragment == null) {
            mPayDialogFragment = PayDialogFragment.getInstance();
        } else {
            UIUtils.dismissDialogFragment(mPayDialogFragment);
        }
        mPayDialogFragment.setData(prepaidRechargeOrder);
        mPayDialogFragment.show(getSupportFragmentManager(), getClass().getSimpleName());
    }

    private void showClearHistoriesDialog() {
        if (mClearHistoriesDialog == null) {
            mClearHistoriesDialog = new ForbiddenBankCardDialog<String>(this)
                    .setTitle(getString(R.string.hint))
                    .setMessage(getString(R.string.clear_historical_recharge_number))
                    .setOnConfirmClickListener(new ForbiddenBankCardDialog.OnConfirmClickListener<String>() {
                        @Override
                        public void onConfirm(String advertId) {
                            UserHelper.clearCurUserPrepaidRechargeHistories();
                            mHistoriesAdapter.clear();
                        }
                    });
        }
        mClearHistoriesDialog.show();
    }

    private ViewTreeObserver.OnGlobalLayoutListener mOnGlobalLayoutListener = new ViewTreeObserver.OnGlobalLayoutListener() {

        //当键盘弹出隐藏的时候会 调用此方法。
        @Override
        public void onGlobalLayout() {
            final Rect rect = new Rect();
            getWindow().getDecorView().getWindowVisibleDisplayFrame(rect);
            final int screenHeight = getWindow().getDecorView().getRootView().getHeight();
            final int heightDifference = screenHeight - rect.bottom;
            boolean visible = heightDifference > screenHeight / 3;
            if (!visible) {
                mEtPhone.getViewTreeObserver().removeOnGlobalLayoutListener(mOnGlobalLayoutListener);
                mEtPhone.setFocusable(false);
                mRecyclerViewHistories.setVisibility(View.GONE);
            }
        }
    };

    private TextWatcherAdapter mPhoneWatcher = new TextWatcherAdapter() {
        @Override
        public void onTextChanged(CharSequence s, int start, int before, int count) {
            mEtPhone.removeTextChangedListener(mPhoneWatcher);
            String phoneNumber = s.toString().trim().replace(" ", "");
            if (DataUtils.isPhoneNumberNotHit(phoneNumber)) {
                mRechargeAdapter.setEnable(true);
                PhoneLocationBean phoneLocation = mPresenter.getPhoneLocation(phoneNumber);
                if (phoneLocation != null) {
                    getPhoneLocationSuccess(phoneNumber, phoneLocation);
                }
            } else {
                mRechargeAdapter.setEnable(false);
                mTvHomeLocation.setText("");
            }
            String newPhoneNumber = formatPhone(phoneNumber);
            mEtPhone.setText(newPhoneNumber);
            mEtPhone.setSelection(newPhoneNumber.length());
            mEtPhone.addTextChangedListener(mPhoneWatcher);
        }
    };

    private String formatPhone(String phoneNumber) {
        if (phoneNumber.length() < 3) return phoneNumber;
        char[] chars = phoneNumber.toCharArray();
        StringBuilder sb = new StringBuilder();
        for (int i = 0; i < chars.length; i++) {
            sb.append(chars[i]).append(i == 2 || i == 6 ? " " : "");
        }
        return sb.toString().trim();
    }

    @Override
    public void requestPrepaidRechargeInfoSuccess(ArrayList<PrepaidGoodsBean> prepaidGoodsBeans) {
        mRechargeAdapter.addAll(true, prepaidGoodsBeans);
    }

    @Override
    public void getPhoneLocationSuccess(String phoneNumber, PhoneLocationBean phoneLocation) {
        String curPhoneNumber = mEtPhone.getText().toString().trim().replace(" ", "");
        if (phoneNumber.equals(curPhoneNumber)) {
            mTvHomeLocation.setText(phoneLocation.getLocation());
        }
    }

    @Override
    public void getPhoneLocationFail(String phoneNumber, String errMessage) {
        mTvHomeLocation.setText("");
    }

    @OnClick({R.id.iv_address_list, R.id.cl_container, R.id.recyclerView, R.id.et_phone})
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.iv_address_list:
                onAddressList();
                break;
            case R.id.cl_container:
            case R.id.recyclerView:
                UIUtils.hideSoftKeyboard(mEtPhone);
                break;
            case R.id.et_phone:
                UIUtils.showSoftKeyboard(mEtPhone);
                showHistoriesPopupWindow();
                mEtPhone.postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        if (mEtPhone != null) {
                            mEtPhone.getViewTreeObserver().addOnGlobalLayoutListener(mOnGlobalLayoutListener);
                        }
                    }
                }, 200);
                break;
        }

    }

    /**
     * 通讯录点击事件
     */
    private void onAddressList() {
        requestPermission(new OnPermissionsResult() {
            @Override
            public void onAllow(List<String> allowPermissions) {
                onSkipContactsUI();
            }

            @Override
            public void onNoAllow(List<String> noAllowPermissions) {
            }

            @Override
            public void onForbid(List<String> noForbidPermissions) {
            }

            @Override
            public void onLowVersion() {
                onSkipContactsUI();
            }
        }, Manifest.permission.READ_CONTACTS);
    }

    private void onSkipContactsUI() {
        startActivityForResult(new Intent(Intent.ACTION_PICK,
                ContactsContract.Contacts.CONTENT_URI), 0);
    }

    public void showHistoriesPopupWindow() {
        if (mHistoriesAdapter.getItems().size() > 0) {
            mRecyclerViewHistories.setVisibility(View.VISIBLE);
        }
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == Activity.RESULT_OK) {
            // ContentProvider展示数据类似一个单个数据库表
            // ContentResolver实例带的方法可实现找到指定的ContentProvider并获取到ContentProvider的数据
            ContentResolver reContentResolverol = getContentResolver();
            // URI,每个ContentProvider定义一个唯一的公开的URI,用于指定到它的数据集
            Uri contactData = data.getData();
            // 查询就是输入URI等参数,其中URI是必须的,其他是可选的,如果系统能找到URI对应的ContentProvider将返回一个Cursor对象.
            Cursor cursor = managedQuery(contactData, null, null, null, null);
            cursor.moveToFirst();
            // 条件为联系人ID
            String contactId = cursor.getString(cursor.getColumnIndex(ContactsContract.Contacts._ID));
            // 获得DATA表中的电话号码，条件为联系人ID,因为手机号码可能会有多个
            Cursor phone = reContentResolverol.query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI, null,
                    ContactsContract.CommonDataKinds.Phone.CONTACT_ID + " = " + contactId, null, null);
            while (phone.moveToNext()) {
                String phoneNumber = phone.getString(phone.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));
                updateSelectedPhone(phoneNumber);
            }
        }
    }

    private void updateSelectedPhone(String phoneNumber) {
        mEtPhone.setText(phoneNumber);
        UIUtils.hideSoftKeyboard(mEtPhone);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        UIUtils.dismissDialog(mClearHistoriesDialog);
    }
}
